package com.sts.panel;

import cn.hutool.core.lang.Singleton;
import com.sts.common.utils.ConfigFileUtil;
import com.sts.common.utils.ImageUtil;
import lombok.Getter;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rtextarea.RTextScrollPane;

import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.*;

/**
 * @author lsl
 * @since 2025年07月17日 19:33
 */
@Getter
public class LogPanel extends JPanel {

    private RSyntaxTextArea logTextArea;
    private JToggleButton lineWrapButton;
    private JButton clearButton;

    public LogPanel() {
        setLayout(new BorderLayout());
        initUI();
        initAction();
    }

    private void initUI() {
        Box centerBox = Box.createHorizontalBox();
        add(centerBox, BorderLayout.CENTER);

        JToolBar toolBar = new JToolBar();
        toolBar.setOrientation(SwingConstants.VERTICAL);
        centerBox.add(toolBar);

        // toolBar里面的按钮组件
        lineWrapButton = new JToggleButton();
        lineWrapButton.setIcon(Singleton.get(ImageUtil.class).getLineWrapIcon());
        toolBar.add(lineWrapButton);

        clearButton = new JButton();
        clearButton.setIcon(Singleton.get(ImageUtil.class).getDeleteIcon());
        toolBar.add(clearButton);

        toolBar.add(Box.createVerticalGlue());

        // 日志文本框
        logTextArea = new RSyntaxTextArea();
        ((DefaultCaret) logTextArea.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        logTextArea.setFont(Singleton.get(ConfigFileUtil.class).getDefaultFont());
        logTextArea.setWrapStyleWord(true);
        logTextArea.setEditable(false);
        RTextScrollPane rTextScrollPane = new RTextScrollPane(logTextArea);
        rTextScrollPane.setLineNumbersEnabled(false);
        centerBox.add(rTextScrollPane);

        // 日志页面下方留白 30 高度
        Box southBox = Box.createVerticalBox();
        southBox.add(Box.createVerticalStrut(30));
        add(southBox, BorderLayout.SOUTH);
    }

    private void initAction() {
        lineWrapButton.addActionListener(e -> logTextArea.setLineWrap(!logTextArea.getLineWrap()));
        clearButton.addActionListener(e -> logTextArea.setText(""));
    }
}
